<?php

namespace App\Console\Commands;

use App\Models\Order;
use App\Models\OrderLease;
use App\Services\OrderService;
use App\Services\RedisService;
use Illuminate\Console\Command;

class WithholdCountCommand extends BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'withholdCountOrder';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '预授权代扣账单统计';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    protected function handleExec()
    {
        $this->queryLease();
    }

    /**
     * 预授权定时扣款统计
     */
    public function queryLease()
    {
        try {
            $where = [
                ['o.pay_type', '!=', Order::ORDER_PAY_TYPE_HUABEI],
                ['ol.begin_time', '<=', time()],
                ['ol.pay_type', OrderLease::LEASE_PAY_TYPE_ZM],
                ['ol.withhold_status', OrderLease::LEASE_WITHHOLD_STATUS_NO],
            ];


            //数据
            $data = Order::from('sp_order_2 as o')
                ->select('o.trade_no', 'ol.id')
                ->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id')
                ->whereIn('o.status', OrderService::getOrderStatus(OrderService::ORDER_WITHHOLD_OR_PAY))
                ->whereIn('ol.status', [OrderLease::ORDER_LEASE_STATUS_NOPAY, OrderLease::ORDER_LEASE_STATUS_OVERDUE])
                ->where($where)
                ->orderBy('ol.id', 'asc')
                ->get();
            $data = obToArray($data);
            if ($data) {
                $leaseId = [];
                foreach ($data as $key => $value) {
                    $leaseId[] = $value['id'];
                }
                if ($leaseId) {
                    RedisService::addRedisList(RedisService::REDIS_QUEUE_KEY_WITHHOLD_COUNT, $leaseId);
                }
                $this->infoLog('预授权定时扣款统计执行成功', $data);
            }
        } catch (\Exception $exception) {
            $this->infoLog('预授权定时扣款统计执行失败' . $exception->getMessage());
        }
    }
}
